package com.smarttiger.zero.admin.service;

import com.smarttiger.zero.admin.dao.BaseDao;
import com.smarttiger.zero.admin.entity.BaseEntity;
import com.smarttiger.zero.admin.util.ParamNames;
import org.springframework.data.domain.Example;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class BaseService<T extends BaseEntity> {

    BaseDao<T> dao;

    public BaseDao<T> getDao() {
        return dao;
    }

    public void setDao(BaseDao<T> dao) {
        this.dao = dao;
    }

    @ParamNames
    public List<T> findAll(){
        List<T> copy = new ArrayList<T>();
        Iterable<T> all = dao.findAll();
        all.forEach(e ->copy.add(e));
        return copy;
    }

    @ParamNames("id")
    public List<T> findById(String id){
        List<T> copy = new ArrayList<T>();
        List<String> ids = new ArrayList<String>();
        ids.add(id);
        Iterable<T> all = dao.findAllById(ids);
        all.forEach(e ->copy.add(e));
        return copy;
    }

    public List<T> findByExample(T t){
        Example<T> example = Example.of(t);
        return dao.findAll(example);
    }

    @Transactional
    public void save(T u){
        if(StringUtils.isEmpty(u.getId())){
            u.setId(UUID.randomUUID().toString());
        }
        if(u.getCreatDate()==null){
            u.setCreatDate(new Date());
        }
        dao.save(u);
    }

    @Transactional
    public void update(T u){
        u.setUpdataDate(new Date());
        dao.save(u);
    }

    @Transactional
    public void delete(String id){
        dao.deleteById(id);
    }
}
